<template>
  <div class="separate-statis-page">
    <div class="question-config">
      <div class="question-config-wrapper">
        <div class="question-config-main">
          <div class="config-item">
            <div class="config-title">
              <div class="xtitle">填写情况</div>
              <div class="xdesc">创建人：{{metaData?.creatorName || 'admin'}} | <span v-if="baseConf?.answerUser?.length>0">{{ baseConf?.answerUser[0]?.value?.map(itm=>itm.name).join(',') }}</span><span v-else>填写人不限</span></div>
              <div class="xbtn" @click="stopResult">{{ metaData?.status === '2' ? '收集中' : (metaData?.status === '1' ? '未发布' : '停止收集') }}</div>
            </div>
            <div class="question-config-tab">
              <div class="xtabitem" :class="{xactive: activeName === 'first'}" 
              @click="activeName = 'first'">
                <div style="font-size: 20px;">{{ resultdata.fillPersonnelNum }}</div>
                <div>填写人数</div>
              </div>
              <div class="xtabitem" :class="{xactive: activeName === 'second'}"
              @click="activeName = 'second'">
                <div style="font-size: 20px;">{{ resultdata.fillResultNum }}</div>
                <div>填写结果</div>
              </div>
              <div class="xtabitem" :class="{xactive: activeName === 'third'}"
              @click="activeName = 'third'" v-if="nuserList?.length">
                <div style="font-size: 20px;">{{ resultdata?.noFillPersonnelNum }}</div>
                <div>未填人数</div>
              </div>
            </div>
            <div class="question-config-bottom" @click="exportData">
              <!-- <div>导出结果</div>
              <div><i-ep-arrow-right /></div> -->
            </div>
          </div>
          <div class="config-item">
            <el-tabs v-model="activeName" class="config-title">
              <el-tab-pane label="数据统计" name="first"></el-tab-pane>
              <el-tab-pane label="已填写" name="second"></el-tab-pane>
              <el-tab-pane label="未填写" name="third" v-if="nuserList?.length"></el-tab-pane>
            </el-tabs>
     
            <div class="question-config-form"
              v-if="activeName === 'first'">
              <div v-for="(item, index) in formList" :key="index" class="form-item">
                <div class="form-item-title" :class="{'mltiny': item.required}"><i class="module-title-required" v-if="item.required">*</i><span v-html="item.title"></span></div>
                <div v-if="item.message" class="form-item-msg">{{ item.message }}</div>
                <div class="form-item-content" v-else-if="item?.options?.length">
                  <div class="xcontent-item" v-for="(opt, idx) in item.options" :key="idx">
                    <div v-html="opt.text"></div>
                    <div>{{ opt.fillNum }}{{ '('+ opt.fillRate+'%)' }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div class="question-user-list"
            v-if="activeName === 'second'">
              <div v-for="(item, index) in userList" :key="index" class="user-item">
                <div @click="openDialog('previewRef', item)">
                  <div class="user-name">{{ item.userName || '匿名' }}</div>
                  <div class="user-time">提交于{{ item.createTime }}</div>
                </div>
                <!-- <a @click="delUserResult(item)" v-if="false">删除</a> -->
              </div>
              <div class="list-pagination" v-if="secondTotal > 0">
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :page-size="20"
                  :total="secondTotal"
                  @current-change="handleSecondChange"
                >
                </el-pagination>
              </div>
            </div>
            <div class="question-user-list"
            v-if="activeName === 'third'&&nuserList?.length">
              <div v-for="(item, index) in nuserList" :key="index" class="user-item">
                <div>
                  <div class="user-name">{{ item.userName || '匿名' }}</div>
                  <div class="user-time">提交于{{ item.createTime }}</div>
                </div>
                <!-- <a>删除</a> -->
              </div>
              <div class="list-pagination">
                <el-pagination
                  background
                  layout="prev, pager, next"
                  :page-size="20"
                  :total="thirdTotal"
                  @current-change="handleThirdChange"
                >
                </el-pagination>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <PreviewDialog ref="previewRef" ></PreviewDialog>
  </div>
  <!-- <div v-else style="width: 100%;">
    <EmptyIndex :data="noDataConfig" />
  </div> -->
</template>

<script setup>
import { ref, onMounted, reactive, computed, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'
// import { noDataConfig } from '@/management/config/analysisConfig'
// import EmptyIndex from '@/management/components/EmptyIndex.vue'
import { dataCountOverview, dataCountUserList, dataCountFillQuestion, exportDataFormResult, dataCountNoUserList, del as deleteById, getExportDataFormResultPath } from '@/management/api/dataform-result'
import { stopForm, startForm } from '@/management/api/dataform'
import { get as _get } from 'lodash-es'
import PreviewDialog from '../components/PreviewDialog.vue'

const route = useRoute()
const store = useStore()

const metaData = computed(() => _get(store.state, 'publishform.schema.metaData'))
const baseConf = computed(() => _get(store.state, 'publishform.schema.baseConf'))
// console.log('metaData1', baseConf.value)
// 打开填写结果弹窗
const previewRef = ref(null)
const openDialog = (ref, val) => {
  // if (ref == "previewRef") previewRef.value?.openDialog(val);
};

const activeName = ref('first')
const resultdata = ref({
  fillPersonnelNum: 0,
  fillResultNum: 0,
  noFillPersonnelNum: 0
})
const formList = ref([])
const userList = ref([])
const secondTotal = ref(0) // 已填写数据总数
const secondPage = ref(1) // 已填写数据当前页
const nuserList = ref([])
const thirdTotal = ref(0) // 已填写数据总数
const thirdPage = ref(1) // 已填写数据当前页

const initData = async () => {
  // try {
    const res = await dataCountOverview({
      formId: route.params.id
    })
 
    if (res?.serverResult?.resultCode === '200') {
      resultdata.value = res?.result || {
        fillPersonnelNum: 0,
        fillResultNum: 0,
        noFillPersonnelNum: 0
      }
    } else {
      ElMessage.error(res?.serverResult?.resultMessage)
    }
  // } catch (error) {
  //   ElMessage.error(error?.message || '查询回收数据失败，请重试')
  // }
  const resp = await dataCountFillQuestion({
    formId: route.params.id
  })

  if (resp?.serverResult?.resultCode === '200') {
    formList.value = resp?.result || []
  } else {
    ElMessage.error(resp?.serverResult?.resultMessage)
  }

  secondPage.value = 1
  await getUserList()

  thirdPage.value = 1
  await getNoUserList()
}
const getUserList = async () => {
  const resu = await dataCountUserList({
    "pageNo": secondPage.value,
    "pageSize": 20,
    condition: { formId: route.params.id }
  })

  if (resu?.serverResult?.resultCode === '200') {
    userList.value = resu?.result?.list || []
    secondTotal.value = resu?.result?.total || 0
  } else {
    ElMessage.error(resu?.serverResult?.resultMessage)
  }
}

const getNoUserList = async () => {
  const resnu = await dataCountNoUserList({
    "pageNo": thirdPage.value,
    "pageSize": 20,
    condition: { formId: route.params.id }
  })

  if (resnu?.serverResult?.resultCode === '200') {
    nuserList.value = resnu?.result?.list || []
    thirdTotal.value = resnu?.result?.total || 0
  } else {
    ElMessage.error(resnu?.serverResult?.resultMessage)
  }
}
const handleSecondChange = async (current) => {
  secondPage.value = current
  await getUserList()
}
const handleThirdChange = async (current) => {
  thirdPage.value = current
  await getNoUserList()
}

const downloadTimer = ref(null)
const exportData = async () => {
  // const res = await exportDataFormResult({
  //   formId: route.params.id
  // })
  // if (res?.serverResult?.resultCode !== '200') {
  //   ElMessage.error(res?.serverResult?.resultMessage)
  //   return
  // }
  // if (res?.result && res?.result !== '0') {
  //   runDownload(res?.result)
  // }
  // ElMessage.success('导出成功')
}
// 开始计时
// const runDownload = (formId) => {
//   if (downloadTimer.value) {
//     clearInterval(downloadTimer.value);
//     downloadTimer.value = null;
//   }
//   downloadTimer.value = setInterval(async () => {
//     try {
//       const res = await getExportDataFormResultPath({
//         formId: formId
//       })
//       if (res?.serverResult?.resultCode !== '200') {
//         ElMessage.error(res?.serverResult?.resultMessage)
//         clearInterval(downloadTimer.value);
//         downloadTimer.value = null;
//       } else if (res?.result && res?.result !== '0') {
//         clearInterval(downloadTimer.value);
//         downloadTimer.value = null;
//         window.$ui.downloadFile2(window.$app.fileBaseUrl+res?.result, metaData.value?.formName?(metaData.value?.formName+'.xlsx'):'form.xlsx')
//       }
//     } catch (error) {
//       clearInterval(downloadTimer.value);
//       downloadTimer.value = null;
//     }
    
//   }, 1000);
// };
// const delUserResult = async (item) => {
//   try {
//     await ElMessageBox.confirm('是否确认删除？', '提示', {
//       confirmButtonText: '确定',
//       cancelButtonText: '取消',
//       type: 'warning'
//     })
//   } catch (error) {
//     return
//   }
//   const res = await deleteById({
//     id: item.batchCode,
//     formId: route.params.id,
//     userId: item.userId
//   })
//   if (res?.serverResult?.resultCode !== '200') {
//     ElMessage.error(res?.serverResult?.resultMessage)
//     return
//   }
//   ElMessage.success('删除成功')
// }
const stopResult = async () => {
  // if (metaData.value?.status === '1') {
  //   return
  // } else if (metaData.value?.status === '2') {
  //   try {
  //     await ElMessageBox.confirm('停止后，填写人无法提交和修改结果！', '即将停止收集', {
  //       confirmButtonText: '停止收集',
  //       cancelButtonText: '取消',
  //       type: 'warning'
  //     })
  //   } catch (error) {
  //     return
  //   }
  //   const res = await stopForm({
  //     formId: route.params.id
  //   })
  //   if (res?.serverResult?.resultCode !== '200') {
  //     ElMessage.error(res?.serverResult?.resultMessage)
  //     return
  //   }
  //   await store.dispatch('publishform/init')
  //   ElMessage.success('停止成功')
  // } else {
  //   const res = await startForm({
  //     formId: route.params.id
  //   })
  //   if (res?.serverResult?.resultCode !== '200') {
  //     ElMessage.error(res?.serverResult?.resultMessage)
  //     return
  //   }
  //   await store.dispatch('publishform/init')
  //   ElMessage.success('开启收集成功')
  // }
  
}

onMounted(initData)
onUnmounted(() => {
  if (downloadTimer.value) {
    clearInterval(downloadTimer.value);
    downloadTimer.value = null;
  }
});
</script>

<style lang="scss" scoped>
.separate-statis-page {
  width: 100%;
  height: 100%;
  // background: #fff;
  // padding: 0 24px;
  // overflow-y: auto;
}
.question-config {
  width: 100%;
  // min-width: 1080px;
  height: 100%;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding: 30px 10px;

  .question-config-wrapper {
    position: relative;
    width: 100%;
    max-width: 798px;
    height: 100%;
    overflow-y: auto;

    .question-config-main {
      :deep(.el-tabs__nav-wrap::after) {
        height: 1px;
      }
      .config-item {
        position: relative;
        margin-bottom: 20px;
        // padding: 19px 32px;
        background-color: $background-color-light;
        border-radius: 12px;
        
        .config-title {
          font-size: 14px;
          color: $font-color-stress;
          .xtitle {
            font-weight: bold;
          }
          .xdesc {
            color: #999;
            font-size: 12px;
            margin-top: 5px;
          }
          .xbtn {
            position: absolute;
            right: 10px;
            top: 10px;
            color: $primary-color;
            font-size: 12px;
            line-height: 12px;
            cursor: pointer;
            padding: 7px 15px 5px 15px;
            border-radius: 10px;
            background: #DFF0FF;
          }

          :deep(.el-tabs__item.is-active) {
            color: #333;
            font-weight: bold;
          }
        }
      }

      .question-config-form {
        // padding-left: 30px;
        padding-top: 15px;
        // padding-right: 1rem;

        .form-item {
          margin-bottom: 20px;
        }
        .form-item-title {
          color: #333;
          display: flex;
          position: relative;
          &.mltiny {
            margin-left: 10px;
          }
          .module-title-required {
            color: #ec4e29;
            left: -10px;
            top: 2px;
            margin-right: 5px;
          }
        }
        .form-item-msg {
          color: #999;
          margin-top: 5px;
        }
        .form-item-content {
          border: 1px solid #e6e6e6;
          border-radius: 8px;
          margin-top: 5px;

          .xcontent-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 15px;
          }
          .xcontent-item:nth-child(even) {
            background: #EBECED;
          }
        }
      }
      .question-user-list {
        .user-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;
          border-bottom: 1px solid #e6e6e6;

          a {
            cursor: pointer;
            font-size: 12px;
            &:hover {
              color: $primary-color;
            }
          }
        }
        .user-name {
          font-size: 16px;
        }
        .user-time {
          color: #999;
        }
      }

      .question-config-tab {
        display: flex;
        align-items: center;
        width: 100%;
        margin-top: 20px;

        .xtabitem {
          width: 100%;
          text-align: center;
          font-size: 12px;
          cursor: pointer;
        }
        .xtabitem.xactive {
          color: $primary-color;
        }
      }

      .question-config-bottom {
        border-top: 1px solid #e6e6e6;
        margin-top: 20px;
        padding: 10px 20px 0 20px;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: space-between;

        &:hover {
          color: $primary-color;
        }
      }
    }
  }
}
.list-pagination {
    margin-top: 20px;
    :deep(.el-pagination) {
      display: flex;
      justify-content: flex-end;
    }
  }
</style>
